package com.andkrup.easygame.ui {
	import flash.display.DisplayObject;	
	import flash.events.MouseEvent;	
	
	import com.andkrup.easygame.game.EasyGameEngine;	
	
	import flash.ui.Keyboard;	
	import flash.events.Event;	
	import flash.events.KeyboardEvent;	
	import flash.geom.Point;	
	
	import com.andkrup.easygame.game.objects.map.IMap;	
	
	import flash.geom.Rectangle;	
	import flash.display.Sprite;
	
	import com.andkrup.easygame.ui.IViewPort;
	
	/**
	 * @author Andkrup
	 */
	public class ViewPort extends Sprite implements IViewPort {
		private static const DEFAULT_WIDTH:uint = 300;
		private static const DEFAULT_HEIGHT:uint = 200;
		
		public function ViewPort() {
			graphics.beginFill(0x333333, 1);
			graphics.drawRect(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);
			graphics.endFill();
			scrollRect = new Rectangle(0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT);
			
			addEventListener(Event.ADDED_TO_STAGE, onLoad, false, 0, true);
		}
		
		private function onLoad(event:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, onLoad);
			stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyAction, false, 0, true);
			stage.addEventListener(KeyboardEvent.KEY_UP, onKeyAction, false, 0, true);
			addEventListener(MouseEvent.MOUSE_UP, onMouseAction, false, 0, true);
			addEventListener(MouseEvent.MOUSE_DOWN, onMouseAction, false, 0, true);
		}

		private function onKeyAction(event:KeyboardEvent):void {
			EasyGameEngine.instance.onKeyCommand(String.fromCharCode(event.charCode).toLowerCase(), event.type, event.shiftKey, event.ctrlKey, event.altKey);
		}
		private function onMouseAction(event:MouseEvent):void {
			EasyGameEngine.instance.onKeyCommand("mouse1", event.type, event.shiftKey, event.ctrlKey, event.altKey);
		}

		public function setSize(width:Number, height:Number):void{
			graphics.clear();
			graphics.beginFill(0x000000, 0);
			graphics.drawRect(0, 0, width, height);
			graphics.endFill();
			scrollRect = new Rectangle(0, 0, width, height);
		}
		
		public function addMap(map:IMap):void{
			addChild(map.sprite);
		}
		
		public function addWorldObject(object:Object, position:Point):void{
//			addChildAt()
		}
		
		public function addCharacterSprite(sprite:DisplayObject, position:Point = null):void{
			addChildAt(sprite, 1);
			if(position){
				sprite.x = position.x;
				sprite.y = position.y;
			}
		}
		
		public function moveTo(p:Point):void{
			
		}
	}
}
